package com.settlement.system.service.impl;

import com.settlement.system.common.enums.FollowUpResponsibilityEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.common.util.SecurityUtils;
import com.settlement.system.common.util.common.SystemUserUtil;
import com.settlement.system.mapper.BaseMapper;
import com.settlement.system.mapper.TblAcsUserRoleAuthorityMapper;
import com.settlement.system.mapper.TblOrderAuditBillDtlMapper;
import com.settlement.system.mapper.TblOrderAuditBillMapper;
import com.settlement.system.mapper.security.userdetails.SysUserDetails;
import com.settlement.system.model.entity.common.*;
import com.settlement.system.model.vo.FinAdjustAccount;
import com.settlement.system.model.vo.ReceiveRefundInfo;
import com.settlement.system.model.vo.SendToReturnInfo;
import com.settlement.system.model.vo.TblOrderAuditBillVo;
import com.settlement.system.service.ITblOrderAuditBillService;
import jakarta.annotation.Resource;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.ResultHandler;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 订单稽核单据主表 服务实现类
 *
 * @author 小船
 * @since 2020-10-21
 */
@Service
public class TblOrderAuditBillServiceImpl extends BaseServiceImpl implements ITblOrderAuditBillService {

    @Resource
    private TblOrderAuditBillMapper tblOrderAuditBillMapper;

    @Resource
    private TblOrderAuditBillDtlMapper tblOrderAuditBillDtlMapper;

    @Resource
    private TblAcsUserRoleAuthorityMapper tblAcsUserRoleAuthorityMapper;

    @Override
    public BaseMapper init() {
        return tblOrderAuditBillMapper;
    }

    @Override
    public int selectBillCount(Map<String, Object> params) throws ServiceException {
        try {
            return tblOrderAuditBillMapper.selectBillCount(params);
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }


    @Override
    public List<TblOrderAuditBill> selectBillByPage(SinglePage singlePage, Map<String, Object> params, String orderByField, String orderBy) throws ServiceException {
        try {
            return tblOrderAuditBillMapper.selectBillByPage(singlePage, params, orderByField, orderBy);
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public TblOrderAuditBillVo selectBillDtl(Map<String, Object> params) throws ServiceException {
        TblOrderAuditBillVo billVo = new TblOrderAuditBillVo();
        try {
            List<TblOrderAuditBill> billList = tblOrderAuditBillMapper.selectByParam(params);
            if (!CollectionUtils.isEmpty(billList)) {
                TblOrderAuditBill bill = billList.get(0);
                List<TblOrderAuditBillDtl> dtlList = tblOrderAuditBillDtlMapper.selectByParam(params);
                PropertyUtils.copyProperties(billVo, bill);
                billVo.setTblOrderAuditBillDtl(dtlList);
                params.put("thirdOrderNo", bill.getSpOrderNo());
                params.put("threeLevelChannelNo", bill.getThreeLevelChannelNo());
                List<ReceiveRefundInfo> receiveRefundInfo = tblOrderAuditBillDtlMapper.getReceiveRefundInfo(params);
                List<SendToReturnInfo> sendToReturnInfo = tblOrderAuditBillDtlMapper.getSendToReturnInfo(params);
                List<FinAdjustAccount> finAdjustAccount = tblOrderAuditBillDtlMapper.getFinAdjustAccount(params);
                setReceiveRefundSum(receiveRefundInfo);
                setSendToReturnSum(sendToReturnInfo);
                billVo.setReceiveRefundInfo(receiveRefundInfo);
                billVo.setSendToReturnInfo(sendToReturnInfo);
                billVo.setFinAdjustAccount(finAdjustAccount);
                billVo.setFollowUpResponsibility(billVo.getFollowUpResponsibility());
                //查询单据下用户是否拥有操作权限
                SysUserDetails user = SecurityUtils.getUser();;
                params.put("authorityNo", "auth_002");
                params.put("loginName", user.getUsername());
                List<TblAcsUserRoleAuthority> allIngo = tblAcsUserRoleAuthorityMapper.getUserByOrderBillNo(params);
                if (CollectionUtils.isEmpty(allIngo)) {
                    billVo.setAuth(false);
                } else {
                    billVo.setAuth(true);
                }
                billVo.setResponsiblePerson(user.getUsername());
            }
            return billVo;
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 责任部门转换
     *
     * @param followUpResponsibility
     * @return
     */
    private String formatFollowUpResponsibility(String followUpResponsibility) {
        StringBuilder result = new StringBuilder();
        if (StringUtils.isNotEmpty(followUpResponsibility)) {
            String[] str = followUpResponsibility.split(",");
            for (int i = 0; i < str.length; i++) {
                result = result.append(FollowUpResponsibilityEnum.getNameByNo(str[i]));
                if (i < str.length - 1) {
                    result = result.append(",");
                }
            }
        }
        return result.toString();

    }

    /**
     * 计算发退货合计
     *
     * @param sendToReturnInfoList
     */
    private void setSendToReturnSum(List<SendToReturnInfo> sendToReturnInfoList) {
        if (!CollectionUtils.isEmpty(sendToReturnInfoList)) {
            SendToReturnInfo sumInfo = new SendToReturnInfo();

            BigDecimal sumAllAmont = BigDecimal.ZERO;
            BigDecimal sumQty = BigDecimal.ZERO;
            sumInfo.setRefBillNo("合计");
            for (SendToReturnInfo sum : sendToReturnInfoList) {
                sumAllAmont = sum.getAmount() == null ? sumAllAmont : sumAllAmont.add(sum.getAmount());
                sumQty = sum.getQty() == null ? sumQty : sumQty.add(sum.getQty());
            }
            sumInfo.setQty(sumQty);
            sumInfo.setAmount(sumAllAmont);
            sendToReturnInfoList.add(sumInfo);
        }
    }

    /**
     * 计算收退款合计
     *
     * @param receiveRefundInfoList
     */
    private void setReceiveRefundSum(List<ReceiveRefundInfo> receiveRefundInfoList) {
        if (!CollectionUtils.isEmpty(receiveRefundInfoList)) {
            ReceiveRefundInfo sumInfo = new ReceiveRefundInfo();
            BigDecimal sumAllAmont = BigDecimal.ZERO;
            sumInfo.setReceiveSendType("合计");
            for (ReceiveRefundInfo sum : receiveRefundInfoList) {
                sumAllAmont = sum.getBillAmount() == null ? sumAllAmont : sumAllAmont.add(sum.getBillAmount());
            }
            sumInfo.setBillAmount(sumAllAmont);
            receiveRefundInfoList.add(sumInfo);
        }
    }

    @Override
    public void getDataBillByHandler(Map<String, Object> params, ResultHandler<TblOrderAuditBill> handler) throws ServiceException {
        try {
            tblOrderAuditBillMapper.getDataBillByHandler(params, handler);
        } catch (Exception ex) {
            throw new ServiceException(ex);
        }
    }

}

